import sqlite3
import os
from datetime import datetime
import base64
from openai import OpenAI
import cv2
import json
import threading

# 导入配置
from config import MODELSCOPE_CONFIG, DATABASE_CONFIG

class AIAnalyzer:
    def __init__(self, db_path=None, api_key=None):
        """初始化AI分析器"""
        self.db_path = db_path or DATABASE_CONFIG['path']
        self.api_key = api_key or MODELSCOPE_CONFIG['api_key']
        self.lock = threading.Lock()  # 添加线程锁
        self.init_database()
        
    def init_database(self):
        """初始化数据库，添加AI分析相关表"""
        with self.lock:  # 使用锁保护数据库初始化
            conn = sqlite3.connect(self.db_path, timeout=20.0)  # 设置连接超时
            cursor = conn.cursor()
            
            # 创建屏幕截图分析记录表
            cursor.execute('''
                CREATE TABLE IF NOT EXISTS screen_analysis (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    device_id TEXT NOT NULL,
                    date TEXT NOT NULL,
                    timestamp TEXT NOT NULL,
                    image_path TEXT NOT NULL,
                    analysis_result TEXT,
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
                )
            ''')
            
            # 创建每日活动总结表
            cursor.execute('''
                CREATE TABLE IF NOT EXISTS daily_activities (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    device_id TEXT NOT NULL,
                    date TEXT NOT NULL,
                    summary TEXT,
                    detailed_analysis TEXT,
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    UNIQUE(device_id, date)
                )
            ''')
            
            conn.commit()
            conn.close()
        
    def analyze_screen_image(self, image_path, device_id, timestamp):
        """分析屏幕截图内容"""
        try:
            # 检查文件是否存在
            if not os.path.exists(image_path):
                print(f"❌ 图像文件不存在: {image_path}")
                return None
                
            # 初始化AI客户端
            client = OpenAI(
                base_url='https://api-inference.modelscope.cn/v1',
                api_key=self.api_key
            )
            
            # 读取图像并转换为base64
            with open(image_path, "rb") as image_file:
                encoded_image = base64.b64encode(image_file.read()).decode('utf-8')
            
            # 调用AI模型分析图像
            response = client.chat.completions.create(
                model=MODELSCOPE_CONFIG['image_model'],
                messages=[{
                    'role': 'user',
                    'content': [{
                        'type': 'text',
                        'text': '请描述这张图片中显示的内容，包括应用程序、文档或网页等信息。'
                    }, {
                        'type': 'image_url',
                        'image_url': {
                            'url': f'data:image/jpeg;base64,{encoded_image}'
                        }
                    }]
                }],
                max_tokens=500
            )
            
            # 获取分析结果
            analysis_result = response.choices[0].message.content
            
            # 保存分析结果到数据库
            self.save_screen_analysis(device_id, timestamp, image_path, analysis_result)
            
            print(f"🧠 已分析屏幕截图: {image_path}")
            return analysis_result
            
        except Exception as e:
            print(f"❌ 屏幕截图分析失败: {e}")
            return None
    
    def save_screen_analysis(self, device_id, timestamp, image_path, analysis_result):
        """保存屏幕截图分析结果"""
        with self.lock:  # 使用锁保护数据库操作
            conn = sqlite3.connect(self.db_path, timeout=20.0)  # 设置连接超时
            cursor = conn.cursor()
            
            dt = datetime.fromisoformat(timestamp)
            date = dt.strftime("%Y-%m-%d")
            
            cursor.execute('''
                INSERT INTO screen_analysis (device_id, date, timestamp, image_path, analysis_result)
                VALUES (?, ?, ?, ?, ?)
            ''', (device_id, date, timestamp, image_path, analysis_result))
            
            conn.commit()
            conn.close()
        
    def generate_daily_summary(self, date):
        """生成每日活动总结"""
        try:
            # 获取当天的所有屏幕分析结果
            analyses = self.get_daily_screen_analyses(date)
            if not analyses:
                print(f"📭 {date} 没有屏幕分析数据")
                return None
                
            # 构建分析提示
            analysis_texts = [f"时间: {analysis[3]}, 内容: {analysis[4]}" for analysis in analyses[:10]]  # 限制数量避免过长
            prompt = f"基于以下{len(analyses)}个时间段的屏幕截图分析结果，请总结这一天的主要活动:\n\n" + "\n".join(analysis_texts)
            prompt += "\n\n请提供一个简洁的总结，包括主要的工作内容、使用的应用程序和活动类型。使用Markdown格式输出。"
            
            # 初始化AI客户端
            client = OpenAI(
                base_url='https://api-inference.modelscope.cn/v1',
                api_key=self.api_key
            )
            
            # 调用AI模型生成总结
            response = client.chat.completions.create(
                model=MODELSCOPE_CONFIG['text_model'],
                messages=[
                    {
                        'role': 'user',
                        'content': prompt
                    }
                ],
                max_tokens=1000
            )
            
            # 获取总结结果
            summary = response.choices[0].message.content
            
            # 保存总结到数据库
            self.save_daily_summary(date, summary)
            
            print(f"📊 已生成 {date} 的活动总结")
            return summary
            
        except Exception as e:
            print(f"❌ 生成每日总结失败: {e}")
            return None
    
    def get_daily_screen_analyses(self, date):
        """获取指定日期的屏幕分析结果"""
        with self.lock:
            conn = sqlite3.connect(self.db_path, timeout=20.0)
            cursor = conn.cursor()
            
            cursor.execute('''
                SELECT * FROM screen_analysis WHERE date = ? ORDER BY timestamp
            ''', (date,))
            
            results = cursor.fetchall()
            conn.close()
            
            return results
    
    def save_daily_summary(self, date, summary):
        """保存每日活动总结"""
        with self.lock:
            conn = sqlite3.connect(self.db_path, timeout=20.0)
            cursor = conn.cursor()
            
            # 这里我们使用一个默认设备ID，因为在多设备情况下需要决定如何处理
            device_id = "default_device"
            
            # 检查是否已存在该日期的总结
            cursor.execute('''
                SELECT id FROM daily_activities WHERE date = ? AND device_id = ?
            ''', (date, device_id))
            
            result = cursor.fetchone()
            if result:
                # 更新现有记录
                cursor.execute('''
                    UPDATE daily_activities 
                    SET summary = ?, detailed_analysis = ?
                    WHERE date = ? AND device_id = ?
                ''', (summary, summary, date, device_id))
            else:
                # 插入新记录
                cursor.execute('''
                    INSERT INTO daily_activities (device_id, date, summary, detailed_analysis)
                    VALUES (?, ?, ?, ?)
                ''', (device_id, date, summary, summary))
            
            conn.commit()
            conn.close()
        
    def get_daily_summary(self, date):
        """获取指定日期的活动总结"""
        with self.lock:
            conn = sqlite3.connect(self.db_path, timeout=20.0)
            cursor = conn.cursor()
            
            cursor.execute('''
                SELECT * FROM daily_activities WHERE date = ?
            ''', (date,))
            
            result = cursor.fetchone()
            conn.close()
            
            return result

# 全局实例
ai_analyzer = AIAnalyzer()

if __name__ == "__main__":
    print("AI分析器已初始化")